package com.zbl.zblproject.core.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zbl.zblproject.contract.entity.Contract;
import com.zbl.zblproject.core.entity.RechargeLog;
import com.zbl.zblproject.core.entity.Result;
import com.zbl.zblproject.core.entity.Supplier;
import com.zbl.zblproject.core.mapper.SupplierMapper;
import com.zbl.zblproject.core.service.SupplierService;
import com.zbl.zblproject.core.utils.ResultUtil;
import com.zbl.zblproject.core.utils.StringUtil;
import com.zbl.zblproject.erp.entity.ErpFinanceLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * @author youlanqiang
 * @version 1.0
 * @date 2018/10/12
 */
@RestController
@RequestMapping("/supplier")
@Api(value = "供应商接口", tags = {"供应商接口"})
public class SupplierController {

    /**
     * 充值凭证图片存放地址
     */
    @Value("${img-path}")
    private String imgPath;

    @Autowired
    private SupplierService supplierService;

    @Autowired
    private SupplierMapper supplierMapper;

    private static final Logger logger = LoggerFactory.getLogger(SupplierController.class);

    @GetMapping("/get-code")
    @ApiOperation("获取供应商的下一个编号")
    public Result getCode(@ApiParam("模式") @RequestParam("bandChangeId") Integer bandChangeId){
        String flowCode = null;
        try {
            if (bandChangeId == 1) {
                //F
                flowCode = supplierService.flowCode("F");
            } else {
                //bandChangeId == 2
                //D
                flowCode = supplierService.flowCode("D");
            }
        }catch(RuntimeException e){
            e.printStackTrace();
            return ResultUtil.error(e.getMessage());
        }
        return ResultUtil.success("成功!", flowCode);
    }


    @PostMapping("/recharge")
    @ApiOperation("用户充值")
    public Result recharge(@ApiParam("供应商ID") @RequestParam("supplierId") int supplierId,
                           @ApiParam("操作人ID") @RequestParam("operatorId") int operatorId,
                           @ApiParam("充值金额") @RequestParam("price") double price,
                           @ApiParam("订单备注") @RequestParam("remarks") String remarks,
                           @ApiParam("凭证图片") @RequestParam("img") MultipartFile file) {
        try {
            if (file == null || file.isEmpty()) {
                return ResultUtil.error("没有上传任何文件!");
            }
            File imgDir = new File(imgPath);
            if (imgDir.exists()) {
                if (imgDir.isFile()) {
                    return ResultUtil.error("保存图片的路径为文件,请通知管理员!");
                }
            } else {
                if (!imgDir.mkdirs()) {
                    return ResultUtil.error("创建保存图片文件夹失败,请联系管理员!");
                }
            }
            String ext = FilenameUtils.getExtension(file.getOriginalFilename());
            if (ext == null) {
                return ResultUtil.error("只支持jpg或png格式的图片!");
            }
            if (!ext.equals("jpg") && !ext.equals("png") && !ext.equals("PNG") && !ext.equals("JPG")) {
                return ResultUtil.error("只支持jpg或png格式的图片!");
            }
            String name = UUID.randomUUID() + "." + ext;
            File targetFile = new File(imgDir, name);
            try {
                file.transferTo(targetFile);
            } catch (IOException e) {
                return ResultUtil.error("保存失败!");
            }

            RechargeLog log = supplierService.recharge(supplierId, operatorId, price, remarks, targetFile.toPath().toString());
            if (log != null) {
                return ResultUtil.success("添加成功");
            }
            return ResultUtil.error("失败");
        } catch (RuntimeException e) {
            return ResultUtil.error(e.getMessage());
        }
    }


    //供应商付款记录
    @GetMapping("/recharge-log/{supplierId}/{current}/{size}")
    @ApiOperation("充值记录")
    public Result rechargeLog(@ApiParam("供应商ID") @PathVariable int supplierId,
                              @ApiParam("页数") @PathVariable int current,
                              @ApiParam("数量") @PathVariable int size) {
        return ResultUtil.success("成功", supplierService.logPage(supplierId, current, size));
    }

    @GetMapping("/{id}")
    @ApiOperation("获取单个供应商")
    public Result one(@ApiParam("供应商ID") @PathVariable Integer id) {
        if (id > 0) {
            return ResultUtil.success("成功!", supplierService.getOneById(id));
        }
        return ResultUtil.error("失败!");
    }

    @GetMapping("/list/{current}/{size}")
    @ApiOperation("供应商列表")
    public Result list(@ApiParam("查询页数") @PathVariable Integer current,
                       @ApiParam("查询数量") @PathVariable Integer size) {
        return ResultUtil.success("成功!", supplierService.erpSupperList(current, size));
    }

    @GetMapping("/list-all")
    @ApiOperation("全部供应商列表")
    public Result listAll() {
        QueryWrapper<Supplier> wrapper = new QueryWrapper<>();
        //wrapper.select("suppliers_id", "suppliers_name");
        return ResultUtil.success("成功!", supplierMapper.selectList(wrapper));
    }

    @GetMapping("/list-search")
    @ApiOperation("供应商查询接口")
    public Result listForSearch(@ApiParam("供应商查询") @RequestParam("context") String context) {
        QueryWrapper<Supplier> wrapper = new QueryWrapper<>();
        //wrapper.select("suppliers_id", "suppliers_name");
        if (!StringUtil.isNullOrEmpty(context)) {
            wrapper.like("suppliers_name", context);
        }
        List<Supplier> supplierList = supplierMapper.selectList(wrapper);
        return ResultUtil.success("成功!", supplierList);
    }


    @PostMapping("/add")
    @ApiOperation("添加一个供应商")
    public Result addSupplier(Supplier supplier,@ApiParam("合同编号") @RequestParam("json") String json) {
        logger.info("供应商信息:{}", JSONObject.toJSON(supplier));
        try {
            supplierService.addSupplier(supplier,json);
            return ResultUtil.success("成功!", supplier);
        } catch (Exception e) {
            return ResultUtil.error(e.getMessage());
        }
    }

    @PostMapping("/update")
    @ApiOperation("更新供应商")
    public Result updateSupplier(Supplier supplier) {
        logger.info("供应商信息:{}", JSONObject.toJSON(supplier));

        if (supplier.getSuppliersId() <= 0) {

            return ResultUtil.error("供应商ID为空.");
        }
        supplier.setStartTime(supplier.getStartTime()/1000);
        supplier.setEndTime(supplier.getEndTime()/1000);
        if (supplierService.updateSupplier(supplier)) {

            return ResultUtil.success("更新成功!");
        }
        return ResultUtil.error("更新失败!");
    }


    @GetMapping("/delete/some")
    @ApiOperation("删除一群供应商")
    public Result delete(@ApiParam("供应商ID集合") @RequestParam("ids") Integer[] array) {
        List<Integer> list = Arrays.asList(array);
        if (list.isEmpty()) {
            return ResultUtil.error("商品ID异常!");
        }
        if (supplierService.deleteSuppliers(list)) {
            return ResultUtil.success("删除成功!");
        } else {
            return ResultUtil.error("删除失败!");
        }
    }

    @GetMapping("/searchSupplierName")
    @ResponseBody
    @ApiOperation("查询用户")
    public Result searchSupplierName(@ApiParam("名称") @RequestParam("name") String name){
        QueryWrapper<Supplier> wrapper = new QueryWrapper<>();
        wrapper.like("suppliers_name",name).or().like("factory_make",name);
        List<Supplier> list = supplierMapper.selectList(wrapper);
        for (Supplier supplier:list){
            List<Contract> contracts = supplierMapper.selectRebateRate(supplier.getSuppliersId());
            if (contracts.size()>0){
                    supplier.setRebateRate(BigDecimal.valueOf(contracts.get(0).getCashBack()));
            }
        }

        return ResultUtil.success("成功", list);
    }


    @GetMapping(value="/export/{ids}",produces = {"application/vnd.ms-excel;charset=UTF-8"})
    @ApiOperation("导出供应商信息")
    public String export(HttpServletResponse response,@PathVariable String ids) throws IOException {
        return supplierService.export(response,ids);
    }

}
